*
*	Run SP-DA
*

local year = "${year}"
global matching_spda_`year'_temp "${data_dir}/Matching_SPDA_{year}_temp.dta"

use "${welfare_analysis_no_err_${year}}", clear

* Run SP-DA
do "${helpers_dir}/runSPDA.do"
save "${matching_spda_${year}_temp}", replace

* Clean-up data
use "${data_for_welfare_analysis_${year}}", clear
	bys applicant_id: egen admitted_applicant = max(admitted)
	keep if (rank == 1 & admitted_applicant == 0) | (admitted == 1)
	replace contract_id = "None" if admitted == 0

	keep id applicant_id contract_id has_justified_envy admitted_below_ps_cutoff

	merge 1:1 id applicant_id using "${matching_spda_${year}_temp}"
	replace contract_id_spda = contract_id if _m == 1 & (has_justified_envy == 1 | admitted_below_ps_cutoff == 1)
	replace contract_id_spda = "None" if _m == 1 & (has_justified_envy != 1 & admitted_below_ps_cutoff != 1) 
	drop _m
save "${data_matching_spda_${year}}", replace

erase "${matching_spda_${year}_temp}"
